<?php
class Market_Model_Xml_XmlGoods_Ruler extends Ub_Ruler_Abstract
{
	protected $_fieldsClass = 'Market_Model_Xml_XmlGoods_Utility_Fields';
    protected $_validatorClass = 'Market_Model_Xml_XmlGoods_Utility_Validate';
    protected $_filterClass = 'Market_Model_Xml_XmlGoods_Utility_Filter';
	protected $_tableClass = 'Market_Model_DbTable_Xml_XmlGoods_Table';
	
	protected $_queryGoods = "";
	protected $_insertQueryGoods = "";
	protected $_enoughLimit = 0;
	protected $_countDebitLimit = 0;
	protected $_onShowcase = 0;
	
	/**
	 * Ставить статус що треба оновляти ціну
	 * @param Market_Model_DbTable_Xml_Row $oUrl
	 * @param unknown_type $status
	 */
	public function updateStatusPrice(Market_Model_DbTable_Xml_Row $oUrl, $status)
	{
		$aUpdate = array();
		$aUpdate['statusUpdatePrice'] = $status;
		
		$oWhere = "";
		$oWhere .= $this->_oTable()->getAdapter()->quoteInto('xmlUrlId = ?', $oUrl->id);
		$oWhere .= ' AND ';
		$oWhere .= $this->_oTable()->getAdapter()->quoteInto("status = ?", Market_Model_DbTable_Xml_XmlGoods_Table::STATUS_UPDATE_PRICE_UPDATED);

		$result = $this->_oTable()->update($aUpdate, $oWhere);
		return $result;
	}
	
	/**
	 * Формує ров для вставки товару
	 * @param Market_Model_Xml_Abstract_Goods $oXmlGoods
	 * @param Market_Model_DbTable_Xml_Row $oXmlUrl
	 * @param unknown_type $aXmlRubRow
	 */
	public function getGoodsRow(Market_Model_Xml_Abstract_Goods $oXmlGoods,
								Market_Model_DbTable_Xml_Row $oXmlUrl,
								$aXmlRubRow)
	{
		$oDate = new Ub_Date(Ub_Date::now());
		$oCurrency = new Ub_Currency();
		
		$oGoods = new Market_Model_DbTable_Goods_Table();
		$oGoodsRow = $oGoods->createRow();
		
//		$oXmlGoods->setCurrentGoodsLang('ua');
        $oXmlGoods->setCurrentGoodsLang( $oXmlUrl->lang );
        $oXmlGoods->setGoodsLang('ua');
		if($oXmlUrl->lang != 'ua')
		{
			$oXmlGoods->setGoodsLang('ua');
		}else 
		{
			$oXmlGoods->setGoodsLang(null);
		}
		$oGoodsRow = $this->_setXmlDataToGoodsRow($oGoodsRow, $oXmlGoods, $oXmlUrl, $aXmlRubRow, null, Ub::STATE_ONPUBLICATION);
		return $oGoodsRow;
	}
	
	/**
	 * Оновляє товари 
	 * @param unknown_type $oXmlUrl
	 * @param unknown_type $aXmlRubRow
	 * @param unknown_type $aXmlGoodsId
	 */
	public function updateXmlGoods(Market_Model_DbTable_Xml_Row $oXmlUrl, $aXmlRubRow, $aXmlGoodsId)
	{
		Ub_Debug::getGenerateTime('початок функції updateXmlGoods');
		$aXmlGoodsId = (array)$aXmlGoodsId;
		if(!count($aXmlGoodsId))
		{
			return array();
		}

		$this->oFields(true)->setXmlUrlId($oXmlUrl->id)
							->setArrayXmlGoodsId($aXmlGoodsId);
		$oXmlGoodsRowset = $this->fetchRowset();

		$aGoodsId = array();
		$aXmlGoodsId = array();
		$isUpdatePrice = false;
		foreach($oXmlGoodsRowset as $oXmlGoodsRow)
		{
			$aGoodsId[] = $oXmlGoodsRow->goodsId;
			$aXmlGoodsId[] = $oXmlGoodsRow->xmlGoodsId;
			if($oXmlGoodsRow->statusUpdatePrice == Market_Model_DbTable_Xml_XmlGoods_Table::STATUS_UPDATE_PRICE_UPDATING)
			{
		   		$isUpdatePrice = true;
		    }
		}

		$oGoods = new Market_Model_DbTable_Goods_Table();
		$oFormatChain = new Market_Model_Goods_Utility_Format_Chain();
		$oGoodsFields = new Market_Model_Goods_Utility_Fields();
		$oGoodsFields->field('parentId', $aGoodsId );
		$oGoodsRowset = $oGoods->get($oFormatChain, $oGoodsFields)->getArrayIdKey();
		if(!count($oGoodsRowset))
		{
			$oGoodsFields = new Market_Model_Goods_Utility_Fields();
			$oGoodsFields->field('id', $aGoodsId);
			$oGoodsRowset = $oGoods->get($oFormatChain, $oGoodsFields)->getArrayIdKey();
		}
		
		$oParser = new Market_Model_Xml_Parser_Controller();

		$aUpdatedGoods = array();
		$aInsertTranslateGoods = array();
		$aXmlGoods = $oParser->parseGoods($oXmlUrl, $aXmlGoodsId);
		
		// Вставляюься обєкти брендів в xml obj goods
		if(!$isUpdatePrice)
		{
			$this->_setBrandToGoodsRow($aXmlGoods);
		}
		
		Ub_Debug::getGenerateTime('до формування масиву ров');
		$query = array();
		$translateQuery = '';
		$insertTranslateQuery = '';
		$aUpdateGoods = array();
		$this->_enoughLimit = $this->_getLimits($oXmlUrl);
		$this->_onShowcase = $oXmlUrl->onShowcase;

		$onShowcase = 'no';
		foreach($oXmlGoodsRowset as $oXmlGoodsRow)
		{
			if(isset($oGoodsRowset[$oXmlGoodsRow->goodsId]))
			{
				if(isset($aXmlGoods[$oXmlGoodsRow->xmlGoodsId]) && $oXmlGoodsRow->statusUpdatePrice == Market_Model_DbTable_Xml_XmlGoods_Table::STATUS_UPDATE_PRICE_UPDATING)
				{
					$aXmlGoods[$oXmlGoodsRow->xmlGoodsId]->setCurrentGoodsLang($oXmlUrl->lang);
					$aXmlGoods[$oXmlGoodsRow->xmlGoodsId]->setGoodsLang(null);
					$resultGoods = $this->_updateGoodsPriceQuery($oGoodsRowset[$oXmlGoodsRow->goodsId]->parentId, $aXmlGoods[$oXmlGoodsRow->xmlGoodsId], $oXmlUrl);
					if($resultGoods === false)
					{
						continue;
					}
					$query[] = $resultGoods;
					$oXmlGoodsRow->status = Market_Model_DbTable_Xml_XmlGoods_Table::STATUS_UPDATED;
					$oXmlGoodsRow->statusUpdatePrice = Market_Model_DbTable_Xml_XmlGoods_Table::STATUS_UPDATE_PRICE_UPDATED;
					$aUpdateGoods = true;
				}
				else if(isset($aXmlGoods[$oXmlGoodsRow->xmlGoodsId]))
				{
					// Клонується товар з хмл без перекладу
					$xmlWithoutTrans = clone $aXmlGoods[$oXmlGoodsRow->xmlGoodsId];
					
					// Товар перекладається на базову мову
					$aXmlGoods[$oXmlGoodsRow->xmlGoodsId]->setCurrentGoodsLang($oXmlUrl->lang);//$oXmlUrl->lang
					if($oXmlUrl->lang != 'ua')
					{
						$aXmlGoods[$oXmlGoodsRow->xmlGoodsId]->setGoodsLang('ua');
					}else 
					{
						$aXmlGoods[$oXmlGoodsRow->xmlGoodsId]->setGoodsLang(null);
					}
					$resultGoods = $this->_updateGoodsQuery($oGoodsRowset[$oXmlGoodsRow->goodsId]->id, $aXmlGoods[$oXmlGoodsRow->xmlGoodsId], $oXmlUrl, $aXmlRubRow, $oGoodsRowset[$oXmlGoodsRow->goodsId]->id, Ub::STATE_PUBLICATED, $onShowcase);
					if($resultGoods === false)
					{
						continue;
					}
					$query[] = $resultGoods;
					$aUpdateGoods[$oGoodsRowset[$oXmlGoodsRow->goodsId]->parentId]['parentId'] = $oGoodsRowset[$oXmlGoodsRow->goodsId]->parentId;
					
					// Фотка з xml
					$aUpdateGoods[$oGoodsRowset[$oXmlGoodsRow->goodsId]->parentId]['photo'] = $aXmlGoods[$oXmlGoodsRow->xmlGoodsId]->getGoodsPhoto();
					
					// Вставляється товар на мові хмл якщо мова хмл не укр
					if($oXmlUrl->lang != 'ua')
					{
						$xmlWithoutTrans->setCurrentGoodsLang($oXmlUrl->lang);
						$xmlWithoutTrans->setGoodsLang(null);
						$oTranslated = $this->_getTranslateForGoods($oGoodsRowset, $oGoodsRowset[$oXmlGoodsRow->goodsId]->parentId);
						if(!$oTranslated)
						{
							$insertTranslateQuery = $this->_insertGoodsQuery($xmlWithoutTrans, $oXmlUrl, $aXmlRubRow, $aUpdateGoods[$oGoodsRowset[$oXmlGoodsRow->goodsId]->parentId]['parentId'], Ub::STATE_PUBLICATED, $onShowcase);
						}
						else if($oTranslated)
						{
							$oTranslateRow = $oTranslated;
							$resultGoods .= $this->_updateGoodsQuery($oTranslateRow->id, $xmlWithoutTrans, $oXmlUrl, $aXmlRubRow, $aUpdateGoods[$oGoodsRowset[$oXmlGoodsRow->goodsId]->parentId]['parentId'], Ub::STATE_PUBLICATED, $onShowcase);
							if($resultGoods !== false)
							{
								$translateQuery .= $resultGoods;
							}
						}
					}
					
					$oXmlGoodsRow->status = Market_Model_DbTable_Xml_XmlGoods_Table::STATUS_UPDATED;
				}
				else
				{
					// Видаляє з допомогою звязку і товар в таблиці xmlGoods
					$oGoodsRowset[$oXmlGoodsRow->goodsId]->delete();
				}
			}
		}
		Ub_Debug::getGenerateTime('після формування масиву update');
		if($query)
		{

			foreach( $query as $q )
			{
			    $oGoods->getAdapter()->query($q);
			}
			
			// Оновлення перекладів
			if($translateQuery)
			{
				$oGoods->getAdapter()->query($translateQuery);
			}
			
			// Вставка перекладів
			if($insertTranslateQuery)
			{    
				$oGoods->getAdapter()->query($insertTranslateQuery);
			}
			
			// Якщо є товари для оновлення то зберігаються картинки і віднімаються ліміти
			if($aUpdateGoods !== true && count($aUpdateGoods) > 0)
			{
				$this->_savePhotos($aUpdateGoods);
				$this->_debitLimits($aUpdateGoods, $oXmlUrl);
			}
			Ub_Debug::getGenerateTime('update в таблиці goods');
			$oXmlGoodsRowset->update();
			Ub_Debug::getGenerateTime('update в таблицю xmlGoods');
			
		}
		return $aUpdateGoods;
	}
	
	protected function _debitLimits($aUpdateGoods, Market_Model_DbTable_Xml_Row $oXmlUrl)
	{
		$aIdForLimit = array();
		foreach ($aUpdateGoods as $key=>$val)
		{
			$aIdForLimit[] = $key;
		}
		$rStorage = new Ads_Model_Storage_Ruler($oXmlUrl->firmId, 'firm');
		
		//if(!$rStorage->debit(count($aIdForLimit), Ub::config(Ub::MODULE_MARKET)->goodsServiceId) )
		
		if( $this->_countDebitLimit && !$rStorage->debit($this->_countDebitLimit, Ub::config(Ub::MODULE_MARKET)->goodsServiceId) )
		{
        	return false;
		}
		return true;
	}
	
	
	protected function _isEnoughLimits($aUpdateGoods, Market_Model_DbTable_Xml_Row $oXmlUrl)
	{
		$aIdForLimit = array();
		foreach ($aUpdateGoods as $key=>$val)
		{
			$aIdForLimit[] = $key;
		}
		
		$rStorage = new Ads_Model_Storage_Ruler($oXmlUrl->firmId, 'firm');

		$countLimits = count($aIdForLimit);
		
		if(!$countLimits)
		{
			return __("Не достаточно лимитов");
		}
		if(!$rStorage->isEnough($countLimits, Ub::config(Ub::MODULE_MARKET)->goodsServiceId))
		{
			return __("Не достаточно лимитов");
		}
	
		return true;
	}
	
	protected function _getLimits(Market_Model_DbTable_Xml_Row $oXmlUrl)
	{
		$rStorage = new Ads_Model_Storage_Ruler($oXmlUrl->firmId, 'firm');
		$result = (integer)$rStorage->getByServiceId(Ub::config(Ub::MODULE_MARKET)->goodsServiceId);
		if($result)
		{
			return $result;
		}
		return false;
	}
	
	/**
	 * Шукає переклад в масиві товарів
	 * Якщо немає перекладу то вертає false
	 * @param unknown_type $aGoodsRow
	 * @param unknown_type $parentId
	 */
	protected function _getTranslateForGoods($aGoodsRow, $parentId)
	{
		foreach($aGoodsRow as $oGoodsRow)
		{
			if($oGoodsRow->parentId != $oGoodsRow->id && $oGoodsRow->parentId == $parentId)
			{
				return $oGoodsRow;
			}
		}
		return false;
	}
	
	/**
	 * Вставляє масив брендів
	 * @param unknown_type $aXmlGoods
	 */
	private function _setBrandToGoodsRow(&$aXmlGoods)
	{
		$aTitles = array();
		
		foreach($aXmlGoods as $oXmlGoods)
		{
			$aTitles[$oXmlGoods->getGoodsVendor()] = $oXmlGoods->getGoodsVendor();
		}
		
		// вставляється бренд якщо його немає інакше просто визначає ід бренда
		$oBrand = new Market_Model_Brand_Ruler_Brand();
		$oBrandRowset = $oBrand->getBrandByArrayTitle($aTitles);
		
		foreach($aXmlGoods as $key => $oXmlGoods)
		{
			foreach($oBrandRowset as $oBrand)
			{
				if($oBrand->title)
				{
					if( stristr($oBrand->title, $oXmlGoods->getGoodsVendor()) )
					{
						$aXmlGoods[$key]->setBrand($oBrand);
						continue; 
					}
				}
			}
		}
		
		$oBrandTable = new Market_Model_DbTable_Brand_Table();
		$aBrandRows = array();
		foreach($aXmlGoods as $oXmlGoods)
		{
			if($oXmlGoods->getBrand() === null)
			{
				$oBrandRow = $oBrandTable->createRow();
				$oBrandRow->title = $oXmlGoods->getGoodsVendor();
				$aBrandRows[] = $oBrandRow;
			}
		}
		
		$oBrandRowset = $oBrandTable->getEmptyRowset();
		$oBrandRowset->setFromRowArray($aBrandRows);
		$oBrandRowset->insert();

		return true;
	}
	
	/**
	 * Формує запрос для вставки товара
	 * @param Market_Model_Xml_Abstract_Goods $oXmlGoods
	 * @param Market_Model_DbTable_Xml_Row $oXmlUrl
	 * @param unknown_type $aXmlRubRow
	 * @param unknown_type $parentId
	 * @param unknown_type $state
	 * @param unknown_type $onShowcase
	 */
	private function _insertGoodsQuery(Market_Model_Xml_Abstract_Goods &$oXmlGoods,
									   Market_Model_DbTable_Xml_Row $oXmlUrl,
									   $aXmlRubRow,
								       $parentId = null,
									   $state = Ub::STATE_PUBLICATED, $onShowcase = 'no')
	{
		$oDate = new Ub_Date(Ub_Date::now());
		$oCurrency = new Ub_Currency();

		if($this->_insertQueryGoods == "")
		{
			$this->_insertQueryGoods = 'INSERT INTO goods (userId, firmId, storeId, slogan, 
											title, des, templateParentId, 
											brandId, barcode, lang, rubParentId, 
											price, priceCurrency, priceSort, 
											wholesalePrice, wholesalePriceCurrency, 
											onShowcase, new, url, creationDate, changeDate, 
											publicationDate, state, parentId) VALUES';
		}
		else 
		{
			$this->_insertQueryGoods .= ', ';
		}
		
		$oTable = new Market_Model_DbTable_Goods_Table();
		$tAdapter = $oTable->getAdapter();
		
		$this->_insertQueryGoods.= '('.$tAdapter->quote($oXmlUrl->userId);
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oXmlUrl->firmId);
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oXmlUrl->storeId);
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oXmlGoods->getGoodsTitle());
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oXmlGoods->getGoodsTitle());
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oXmlGoods->getGoodsDescription());
		$this->_insertQueryGoods.= ', '.'null';
		if($oXmlGoods->getBrand() && $oXmlGoods->getBrand()->id)
		{
			$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oXmlGoods->getBrand()->id);
		}
		else 
		{
			$this->_insertQueryGoods.= ', '.'NULL';
		}
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oXmlGoods->getGoodsBarcode());
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oXmlGoods->getGoodsLang());
		
		if(isset($aXmlRubRow[$oXmlGoods->getGoodsRubId()]))
		{
			$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($aXmlRubRow[$oXmlGoods->getGoodsRubId()]->rubId);
		}
			
		$aPrice = $oXmlGoods->getGoodsPrice();
		if(isset($aPrice['price']) && isset($aPrice['currency']))
        {
        	$aPrice['price'] = $aPrice['price'] ? $aPrice['price'] : 1;
			$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($aPrice['price']);
			$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($aPrice['currency']);
			$this->_insertQueryGoods.= ', '.''.$tAdapter->quote(($oCurrency->getConvert($aPrice['price'], $aPrice['currency'], 'UAH', Ub_Currency::SIMPLE)*100));
			$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($aPrice['price']);
			$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($aPrice['currency']);
        }
        	
			
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($onShowcase);
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote('yes');
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oXmlGoods->getGoodsUrl());
			
			
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oDate->getFormatedDate(Ub_Date::UB_DATETIME));
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oDate->getFormatedDate(Ub_Date::UB_DATETIME));
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($oDate->getFormatedDate(Ub_Date::UB_DATETIME));
		$this->_insertQueryGoods.= ', '.''.$tAdapter->quote(Ub::STATE_PUBLICATED);
			
		if($parentId)
		{
			$this->_insertQueryGoods.= ', '.''.$tAdapter->quote($parentId);
		}
		
		$this->_insertQueryGoods .= ')';

		return $this->_insertQueryGoods;
	}
	
	/**
	 * формує запит для оновлення товарів
	 * @param unknown_type $id
	 * @param unknown_type $oXmlGoods
	 * @param unknown_type $oXmlUrl
	 * @param unknown_type $aXmlRubRow
	 * @param unknown_type $parentId
	 * @param unknown_type $state
	 * @param unknown_type $onShowcase
	 */
	private function _updateGoodsQuery($id, Market_Model_Xml_Abstract_Goods &$oXmlGoods,
									   Market_Model_DbTable_Xml_Row $oXmlUrl,
									   $aXmlRubRow,
								       $parentId = null,
									   $state = Ub::STATE_PUBLICATED, &$onShowcase = 'no')
	{
		if(!isset($aXmlRubRow[$oXmlGoods->getGoodsRubId()]) || $aXmlRubRow[$oXmlGoods->getGoodsRubId()]->rubId <= 0 )
		{
			return false;
		}
		
		$oDate = new Ub_Date(Ub_Date::now());
		$oCurrency = new Ub_Currency();

		$this->_queryGoods = 'UPDATE goods SET ';
		
		$oTable = new Market_Model_DbTable_Goods_Table();
		$tAdapter = $oTable->getAdapter();
		
		$where = ' WHERE id='.$tAdapter->quote($id);
		
		$this->_queryGoods.= 'userId='.$tAdapter->quote($oXmlUrl->userId);
		$this->_queryGoods.= ', '.'firmId='.$tAdapter->quote($oXmlUrl->firmId);
		$this->_queryGoods.= ', '.'storeId='.$tAdapter->quote($oXmlUrl->storeId);
		$this->_queryGoods.= ', '.'slogan='.$tAdapter->quote($oXmlGoods->getGoodsTitle());
		$this->_queryGoods.= ', '.'title='.$tAdapter->quote($oXmlGoods->getGoodsTitle());
		$this->_queryGoods.= ', '.'des='.$tAdapter->quote($oXmlGoods->getGoodsDescription());
		$this->_queryGoods.= ', '.'templateParentId=null';
		
		if($oXmlGoods->isNotTranslated())
		{
			return false;
		}
		
		if($oXmlGoods->getBrand() && $oXmlGoods->getBrand()->id)
		{
			$this->_queryGoods.= ', '.'brandId='.$tAdapter->quote($oXmlGoods->getBrand()->id);
		}
		else 
		{
			$this->_queryGoods.= ', '.'brandId=NULL';
		}
		$this->_queryGoods.= ', '.'barcode='.$tAdapter->quote($oXmlGoods->getGoodsBarcode());
		$this->_queryGoods.= ', '.'lang='.$tAdapter->quote($oXmlGoods->getGoodsLang());
		
		if(isset($aXmlRubRow[$oXmlGoods->getGoodsRubId()]))
		{
			$this->_queryGoods.= ', '.'rubParentId='.$tAdapter->quote($aXmlRubRow[$oXmlGoods->getGoodsRubId()]->rubId);
		}
			
		$aPrice = $oXmlGoods->getGoodsPrice();
		if(isset($aPrice['price']) && isset($aPrice['currency']))
        {
        	$aPrice['price'] = $aPrice['price'] ? $aPrice['price'] : 1;
			$this->_queryGoods.= ', '.'price='.$tAdapter->quote($aPrice['price']);
			$this->_queryGoods.= ', '.'priceCurrency='.$tAdapter->quote($aPrice['currency']);
			$this->_queryGoods.= ', '.'priceSort='.$tAdapter->quote(($oCurrency->getConvert($aPrice['price'], $aPrice['currency'], 'UAH', Ub_Currency::SIMPLE)*100));
			$this->_queryGoods.= ', '.'wholesalePrice='.$tAdapter->quote($aPrice['price']);
			$this->_queryGoods.= ', '.'wholesalePriceCurrency='.$tAdapter->quote($aPrice['currency']);
        }
        	
        if(($this->_enoughLimit > 0 && $this->_onShowcase > 0))
        {
        	$onShowcase = 'yes';
        	$this->_countDebitLimit++;
        	$this->_enoughLimit--;
        	$this->_onShowcase--;
        }
		$this->_queryGoods.= ', '.'onShowcase='.$tAdapter->quote($onShowcase);
		$this->_queryGoods.= ', '.'new='.$tAdapter->quote('yes');
		$this->_queryGoods.= ', '.'url='.$tAdapter->quote($oXmlGoods->getGoodsUrl());
			
			
		$this->_queryGoods.= ', '.'creationDate='.$tAdapter->quote($oDate->getFormatedDate(Ub_Date::UB_DATETIME));
		$this->_queryGoods.= ', '.'changeDate='.$tAdapter->quote($oDate->getFormatedDate(Ub_Date::UB_DATETIME));
		$this->_queryGoods.= ', '.'publicationDate='.$tAdapter->quote($oDate->getFormatedDate(Ub_Date::UB_DATETIME));
		$this->_queryGoods.= ', '.'state='.$tAdapter->quote(Ub::STATE_PUBLICATED);
			
		if($parentId)
		{
			$this->_queryGoods.= ', '.'parentId='.$tAdapter->quote($parentId);
		}
		
		$this->_queryGoods .= $where;
		$this->_queryGoods .= ';';
		
		return $this->_queryGoods;
	}
	
	/**
	 * Формує запит для оновлення цін товарів
	 * @param unknown_type $parentId
	 * @param Market_Model_Xml_Abstract_Goods $oXmlGoods
	 * @param Market_Model_DbTable_Xml_Row $oXmlUrl
	 */
	private function _updateGoodsPriceQuery($parentId, Market_Model_Xml_Abstract_Goods &$oXmlGoods,
										    Market_Model_DbTable_Xml_Row $oXmlUrl)
	{
		$oDate = new Ub_Date(Ub_Date::now());
		$oCurrency = new Ub_Currency();

		$this->_queryGoods = 'UPDATE goods SET ';
		
		$oTable = new Market_Model_DbTable_Goods_Table();
		$tAdapter = $oTable->getAdapter();
		
		$where = ' WHERE parentId='.$tAdapter->quote($parentId);
		
		$aPrice = $oXmlGoods->getGoodsPrice();
		if(isset($aPrice['price']) && isset($aPrice['currency']))
        {
        	$aPrice['price'] = $aPrice['price'] ? $aPrice['price'] : 1;
			$this->_queryGoods.= ' '.'price='.$tAdapter->quote($aPrice['price']);
			$this->_queryGoods.= ', '.'priceCurrency='.$tAdapter->quote($aPrice['currency']);
			$this->_queryGoods.= ', '.'priceSort='.$tAdapter->quote(($oCurrency->getConvert($aPrice['price'], $aPrice['currency'], 'UAH', Ub_Currency::SIMPLE)*100));
			$this->_queryGoods.= ', '.'wholesalePrice='.$tAdapter->quote($aPrice['price']);
			$this->_queryGoods.= ', '.'wholesalePriceCurrency='.$tAdapter->quote($aPrice['currency']);
        }
        
		$this->_queryGoods .= $where;
		$this->_queryGoods .= '; ';

		return $this->_queryGoods;
	}
	
	/**
	 * Формує обєкт ров XmlGoods
	 * @param unknown_type $xmlGoodsId
	 * @param unknown_type $goodsId
	 * @param unknown_type $xmlUrlId
	 */
	public function getXmlGoodsRow($xmlGoodsId, $goodsId, $xmlUrlId)
	{
		$oXmlGoodsRow = $this->_oTable()->createRow();
		$oXmlGoodsRow->xmlGoodsId = $xmlGoodsId;
		$oXmlGoodsRow->goodsId = $goodsId;
		$oXmlGoodsRow->xmlUrlId = $xmlUrlId;
		return $oXmlGoodsRow;
	}
	
	/**
	 * Зберігає картинки
	 * @param unknown_type $goodsRowset
	 */
	private function _savePhotos($goodsRowset)
	{
		Ub_Debug::getGenerateTime('початок зберігання фото');
		
		// Зберігаю фото
		$socket = new Ub_Socket();
		$tPhoto = new Market_Model_DbTable_Goods_Photos_Table();
		$savedPhotos = array();
		
		$aGoodsId = array();
		foreach($goodsRowset as $key => $goods)
		{
			$aGoodsId[] = $goods['parentId'];
		}
		
		$oPhotosRowset = $tPhoto->getByGoods($aGoodsId);
		$aIdForRemove = array();
		foreach($aGoodsId as $gId)
		{
			if(isset($oPhotosRowset[$gId]) && $oPhotosRowset[$gId])
			{
				foreach($oPhotosRowset[$gId] as $oPhoto)
				{
					if(isset($oPhoto->src) && $oPhoto->src)
			        {
			            $arr=explode('/', $oPhoto->src);
		                $res=$socket->removeFileInModule($arr[1], Ub::MODULE_MARKET, $arr[0], 'photos');
			        	$aIdForRemove[] = $oPhoto->id;
					}
				}
			}
		}
		if($aIdForRemove)
		{
			$res = $tPhoto->deleteById($aIdForRemove);
		}
		
		$aPhotos = array();
		foreach($goodsRowset as $key => $goods)
		{
			if($goods['photo'])
			{
				$aPhotos[$goods['parentId']] = $goods['photo'];
			}
		}
		
		if( $aPhotos )
		{
    		$aNewPhotos = $socket->uploadFilesInModule($aPhotos, 'photos', Ub::MODULE_MARKET);
    		
    		$insertQuery = "INSERT INTO gPhotos (goodsParentId, src) VALUES";
    		$values = "";
    		foreach($aNewPhotos as $goodsId => $photo)
    		{
    			if(isset($photo->status) && $photo->status && isset($photo->dir) && isset($photo->fileName))
                {
                	if($values != "")
                	{
                		$values .= ", ";
                	}
                	$values .= "(";
                	$values .= $tPhoto->getAdapter()->quote($goodsId).", ";
                	$values .= $tPhoto->getAdapter()->quote($photo->dir.DS.$photo->fileName);
    	            $values .= ")";
                }
    		}
    		
    		$insertQuery .= $values;
    		$tPhoto->getAdapter()->query($insertQuery);
		}
		
		Ub_Debug::getGenerateTime('кінець зберігання фото');
		return true;
	}
	
	/**
	 * Формує ров для вставки або для оновлення
	 * Використовується зараз тільки для вставки
	 * @param Market_Model_DbTable_Goods_Row $oGoodsRow
	 * @param Market_Model_Xml_Abstract_Goods $oXmlGoods
	 * @param Market_Model_DbTable_Xml_Row $oXmlUrl
	 * @param unknown_type $aXmlRubRow
	 * @param unknown_type $parentId
	 * @param unknown_type $state
	 */
	private function _setXmlDataToGoodsRow(Market_Model_DbTable_Goods_Row $oGoodsRow,
										   Market_Model_Xml_Abstract_Goods $oXmlGoods,
										   Market_Model_DbTable_Xml_Row $oXmlUrl,
										   $aXmlRubRow,
										   $parentId = null,
										   $state = Ub::STATE_PUBLICATED)
	{
		$oDate = new Ub_Date(Ub_Date::now());
		$oCurrency = new Ub_Currency();
		
		$oGoodsRow->setFromArray($oXmlGoods->toGoodsArray());
		
		if(isset($aXmlRubRow[$oXmlGoods->getGoodsRubId()]))
		{
			$oGoodsRow->rubParentId = $aXmlRubRow[$oXmlGoods->getGoodsRubId()]->rubId;
		}
		
		if($oXmlGoods->getBrand() !== null)
		{
			$oGoodsRow->brandId = $oXmlGoods->getBrand()->id;//$oBrandRow->id;
		}
		$oGoodsRow->barcode = '';
		$oGoodsRow->onShowcase = 'no';
        $oGoodsRow->new = 'yes';
        
        $oGoodsRow->templateParentId = null;
        $oGoodsRow->unitParentId = 1;
        $oGoodsRow->availableUnitParentId = 1;
        $oGoodsRow->available = 1;

        $price = $oXmlGoods->getGoodsPrice();
        if(isset($price['price']) && isset($price['currency']))
        {
	        $oGoodsRow->priceSort = $oCurrency->getConvert($price['price'] ? $price['price'] : 1, $price['currency'], 'UAH', Ub_Currency::SIMPLE) * 100;
	        $oGoodsRow->wholesalePrice = $price['price'];
	        $oGoodsRow->wholesalePriceCurrency = $price['currency'];
        }
        $oGoodsRow->wholesaleUnitParentId = 1;
        $oGoodsRow->minWholesaleParcel = 1;
        
		$oGoodsRow->creationDate = $oDate->getFormatedDate(Ub_Date::UB_DATETIME);
		$oGoodsRow->changeDate = $oDate->getFormatedDate(Ub_Date::UB_DATETIME);
		$oGoodsRow->state = $state;
		$oGoodsRow->storeId = $oXmlUrl->storeId;
		$oGoodsRow->userId = $oXmlUrl->userId;
		$oGoodsRow->firmId = $oXmlUrl->firmId;
		if($parentId)
		{
			$oGoodsRow->parentId = $parentId;
		}
		
		return $oGoodsRow;
	}	
	
	protected function _saveProperties(Market_Model_DbTable_Goods_Row $oGoodsRow,
									   Market_Model_Xml_Abstract_Goods $oXmlGoods,
									   Market_Model_DbTable_Xml_Row $oXmlUrl)
	{
	}
	
	private function _copyFileToTmp($url)
	{
		if(is_array($url))
		{
			print_r($url); exit();
		}
		$file = file_get_contents($url);
		$nextFolder = Ub::config()->path->data."/tmp/";
		$fileName = substr(strrchr($url, '/'), 1);
		if(!$fileName)
		{
			$fileName = md5(time()).'jpg';
		}
		$fhandle = fopen($nextFolder.$fileName, "w");
		fwrite($fhandle, $file);
		fclose($fhandle);
		return $fileName;
	}
	
	
	
	
	
	
	
	
	
	
}